import 'package:flutter/foundation.dart';

import 'native_device_info.dart' if (dart.library.html) 'web_device_info.dart'
    as platform_worker;

class FlutterDeviceInfo {
  FlutterDeviceInfo._();

  static FlutterDeviceInfo _singleton = FlutterDeviceInfo._();

  static FlutterDeviceInfo get singleton => _singleton;
  final Map<String, dynamic> _deviceCacheInfo = Map();

  String get userAgent => _deviceCacheInfo['userAgent'];

  String get webViewUserAgent =>
      _deviceCacheInfo['webViewUserAgent'] ?? userAgent;

  String get deviceName => _deviceCacheInfo['deviceName'];

  bool get isIOS => _deviceCacheInfo['isIOS'] ?? false;

  bool get isAndroid => _deviceCacheInfo['isAndroid'] ?? false;

  bool get isPCWeb {
    if (kIsWeb == false) {
      return false;
    }
    if (isIOS || isAndroid) {
      return false;
    }
    return true;
  }

  bool get isXiaomi => _deviceCacheInfo['xiaomi'] ?? false;

  Future loadDeviceInfo() async {
    final info = await platform_worker.loadDeviceInfo();
    _deviceCacheInfo.addAll(info);
    _deviceCheck();
    debugPrint(_deviceCacheInfo.toString());
  }

  void _deviceCheck() {
    _deviceCacheInfo['xiaomi'] = hasDeviceTag(['miui', 'xiaomi', 'redmi']);
  }

  bool hasDeviceTag(List<String> deviceTags, {bool matchCase = false}) {
    final userAgentL =
        (matchCase == false) ? userAgent.toLowerCase() : userAgent;
    final webViewUserAgentL = (matchCase == false)
        ? webViewUserAgent.toLowerCase()
        : webViewUserAgent;

    for (int i = 0; i < deviceTags.length; ++i) {
      final element =
          (matchCase == false) ? deviceTags[i].toLowerCase() : deviceTags[i];
      if (userAgentL.contains(element) || webViewUserAgentL.contains(element)) {
        return true;
      }
    }
    return false;
  }
}
